package com.douding.server.service;

import com.douding.server.domain.Chapter;
import com.douding.server.domain.ChapterExample;
import com.douding.server.dto.ChapterDto;
import com.douding.server.dto.ChapterPageDto;
import com.douding.server.dto.PageDto;
import com.douding.server.mapper.ChapterMapper;
import com.douding.server.util.CopyUtil;
import com.douding.server.util.UuidUtil;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChapterService {

    @Resource
    private ChapterMapper chapterMapper;

    public void list(ChapterPageDto chapterPageDto){
//        PageHelper.startPage(chapterPageDto.getPage(), chapterPageDto.getSize());
        ChapterExample chapterExample = new ChapterExample();
        List<Chapter> resList = new ArrayList<>();
        // 获取chapter列表
        List<Chapter> chapterList = chapterMapper.selectByExample(chapterExample);
        for (Chapter each: chapterList) {
            String courseId = each.getCourseId();
            if (courseId.equals(chapterPageDto.getCourseId())) {
                resList.add(each);
            }
        }
        chapterPageDto.setList(resList);
    }// method


    public void save(ChapterDto chapterDto) {
        Chapter chapter = CopyUtil.copy(chapterDto, Chapter.class);
        if (StringUtils.isEmpty(chapter.getId())) {
            this.insert(chapter);
        } else {
            this.update(chapter);
        }


    }
    //新增数据
    private void insert(Chapter chapter) {
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insert(chapter);
    }
    //更新数据
    private void update(Chapter chapter) {
        chapterMapper.updateByPrimaryKey(chapter);
    }

    public void delete(String id) {
        chapterMapper.deleteByPrimaryKey(id);
    }


    /**
     * 查询某一课程下的所有章
     */
    public List<ChapterDto> listByCourse(String courseId) {
        ChapterExample chapterExample = new ChapterExample();
        List<ChapterDto> resList = new ArrayList<>();
        List<Chapter> chapterList = chapterMapper.selectByExample(chapterExample);
        for (Chapter each: chapterList) {
            if (courseId.equals(each.getCourseId())) {
                resList.add(CopyUtil.copy(each, ChapterDto.class));
            }
        }

        return resList;
    }
}//end class
